package com.campus.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.pojo.Grade;
import com.campus.service.GradeService;
import com.campus.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/sms/gradeController")
public class GradeController {
    @Resource
    private GradeService gradeService;

    /**
     * 分页带条件查询年级信息
     * @param pn  当前页码
     * @param pageSize  每页显示记录数
     * @param gradeName  请求参数中模糊查询的条件封装
     * @return
     */
    @GetMapping("/getGrades/{pn}/{pageSize}")
    public Result<Object> getGrades( @PathVariable("pn") Integer pn,
                                    @PathVariable("pageSize") Integer pageSize,
                                    String gradeName) {
        //判断gradeName是否有值 若有值 则需要根据条件进行分页
        if (gradeName == null) {
            //根据当前页 以及每页显示的记录数 获取Page对象
            Page<Grade> page = gradeService.page(new Page<>(pn, pageSize),new LambdaQueryWrapper<Grade>().orderByDesc(Grade::getId));
            return Result.ok(page);
        }
        LambdaQueryWrapper<Grade> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Grade::getName, gradeName).orderByDesc(Grade::getId);
        Page<Grade> page = gradeService.page(new Page<>(pn, pageSize), lambdaQueryWrapper);
        return Result.ok(page);
    }

    /**
     * 根据id进行删除 或者批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteGrade")
    public Result<Object>deleteGrades(@RequestBody List<Integer> ids){
        if(ids.size()==1){
            //如果集合只有一个那么就代表只有一条记录  只需要执行删除单个id
            gradeService.removeById(ids.get(0));
        }else{
            //多条记录 那么就要删除集合
            gradeService.removeBatchByIds(ids);
        }
        return Result.ok();
    }

    /**
     * 存储或者更新年级信息
     * @param grade  封装到实体类的请求体中json数据
     * @return
     */
    @PostMapping("/saveOrUpdateGrade")
    public Result<Object> saveOrUpdateGrade( @RequestBody Grade grade) {
        //查这个id是否存在，如果存在那么就执行更新操作，如果不存在那么就执行添加操作
        Integer id = grade.getId();
        if (id == null) {
            gradeService.save(grade);
        } else {
            gradeService.update(grade, new LambdaQueryWrapper<Grade>().eq(Grade::getId, id));
        }
        return Result.ok();
    }

    //获取所有年级的JSON
    @GetMapping("/getGrades")
    public Result<Object> getGrades(){
        List<Grade> grades = gradeService.list(new LambdaQueryWrapper<Grade>().orderByDesc(Grade::getId));
        return Result.ok(grades);
    }

}
